package com.softdev.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.softdev.common.R;
import com.softdev.dto.ProjectDto;
import com.softdev.dto.ProjectResultDto;
import com.softdev.service.ProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api("项目操作")
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @ApiOperation("新建项目")
    @PreAuthorize("hasRole('ROLE_manager')")
    @PostMapping
    public R<String> add(@RequestBody ProjectDto projectDto) {

        if (projectService.add(projectDto)) {
            return R.success("项目创建成功！");
        }
        return R.error("项目创建失败...");
    }

    @ApiOperation("获取单个项目")
    @GetMapping
    public R<ProjectResultDto> get(Long projectId) {

        ProjectResultDto resultDto = projectService.get(projectId);

        return R.success(resultDto);
    }

    @ApiOperation("分页查询项目")
    @GetMapping("/page")
    public R<Page<ProjectResultDto>> page(int page , int size) {

        Page<ProjectResultDto> projects = projectService.page(page, size);

        return R.success(projects);
    }

    @ApiOperation("更新项目进度")
    @PreAuthorize("hasRole('ROLE_manager')")
    @PutMapping
    public R<String> update(Long projectId) throws JsonProcessingException {

        if (projectService.update(projectId)) {
            return R.success("项目状态更新成功！");
        }

        return R.error("有部门未完成任务或其他错误...");
    }

}
